package com.xdwanj.volleytest.repo;

import android.content.Context;
import android.graphics.Bitmap;
import android.util.Log;

import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageRequest;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;
import com.google.gson.Gson;
import com.xdwanj.volleytest.data.Banner;
import com.xdwanj.volleytest.data.result.ResultBanner;
import com.xdwanj.volleytest.data.result.ResultNewsCategory;
import com.xdwanj.volleytest.data.result.ResultUser;
import com.xdwanj.volleytest.data.TokenUser;
import com.xdwanj.volleytest.util.EncodedUtils;

import org.json.JSONObject;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class TestRepository implements ITestRepository {
    private static final String TAG = "TestRepository";
    private static final String URL = "http://124.93.196.45:10001";
    private static String TOKEN = "eyJhbGciOiJIUzUxMiJ9.eyJsb2dpbl91c2VyX2tleSI6IjFhOWE4ZTA3LWZiOTYtNDAzMy1hMTY0LTE3ZDBiYzMyNTUxOCJ9.ziCrQswQyU5F_h3MlR8ltA_03c_9TOS2FUUWgr2BUJaUih7BtW9AA0LqVvWoAFnUDq8dHcvI37jYTKZf-BYCoQ";
    private static final String HEADER_AUTHORIZATION = "Authorization";

    private static RequestQueue mQueue;
    private static TestRepository INSTANCE = null;

    private TestRepository() {

    }

    public static TestRepository getInstance() {
        if (INSTANCE != null) {
            return INSTANCE;
        } else {
            throw new IllegalStateException("TestRepository is not init");
        }
    }

    public static void init(RequestQueue queue) {
        INSTANCE = new TestRepository();
        mQueue = queue;
    }

    //----------------------------------------------------------------------

    public LiveData<ResultNewsCategory> ListNewsCategory(Context context) {
        Gson gson = new Gson();
        MutableLiveData<ResultNewsCategory> liveData = new MutableLiveData<>();
        StringRequest request = new StringRequest(Request.Method.GET, URL + "/prod-api/press/category/list",
                response -> {
                    Log.d(TAG, "ListNewsCategory: " + EncodedUtils.IsoToUtf8(response));
                    liveData.setValue(gson.fromJson(EncodedUtils.IsoToUtf8(response), ResultNewsCategory.class));
                },
                error -> Log.d(TAG, "onErrorResponse: " + error)
        );
        request.setTag("hello");
        mQueue.add(request);

        return liveData;
    }

    public LiveData<String> login(TokenUser user) {
        String url = URL + "/prod-api/api/login";
        Gson gson = new Gson();

        Map<String, String> map = new HashMap<>();
        map.put("username", user.getUsername());
        map.put("password", user.getPassword());
        JSONObject jsonObject = new JSONObject(map);

        MutableLiveData<String> liveData = new MutableLiveData<>();

        StringRequest request = new StringRequest(Request.Method.POST, url,
                response -> {
                    Log.d(TAG, "onResponse: " + EncodedUtils.IsoToUtf8(response));
                    liveData.setValue(response);
                },
                error -> Log.d(TAG, "onErrorResponse: " + error)
        ) {
            @Override
            public String getBodyContentType() {
                return "application/json; charset=" + getParamsEncoding();
            }

            @Override
            public byte[] getBody() throws AuthFailureError {
                return EncodedUtils.Utf8ToIso(gson.toJson(user)).getBytes(StandardCharsets.ISO_8859_1);
            }
        };

        mQueue.add(request);

//        mRequestQueue.add(new StringRequest(Request.Method.POST, url,
//                response -> {
//                    LoginResult result = gson.fromJson(response, LoginResult.class);
//                    Log.d(TAG, "onResponse: result->" + result);
//                    Log.d(TAG, "onResponse: response->" + response);
//                    liveData.setValue(result.token);
//                },
//                error -> {
//                    Log.d(TAG, "onErrorResponse: " + error.toString());
//                }
//        ) {
//            @Override
//            public String getBodyContentType() {
//                return "application/json;charset=" + getParamsEncoding();
//            }
//
//            @Override
//            public byte[] getBody() throws AuthFailureError {
//                return gson.toJson(user).getBytes();
//            }
//
//        });
        return liveData;
    }

    // 使用StringRequest
    public LiveData<ResultUser> getUser_1(Context context) {
        MutableLiveData<ResultUser> liveData = new MutableLiveData<>();
        Gson gson = new Gson();

        mQueue.add(new StringRequest(Request.Method.GET, URL + "/prod-api/api/common/user/getInfo",
                response -> {
                    Log.d(TAG, "onResponse: " + response);
                    liveData.setValue(gson.fromJson(response, ResultUser.class));
                },
                error -> Log.d(TAG, "onErrorResponse: " + error)
        ));

        return liveData;
    }

    // 使用JsonObjectRequest
    public LiveData<ResultUser> getUser(Context context) {
        MutableLiveData<ResultUser> liveData = new MutableLiveData<>();
        Gson gson = new Gson();

        mQueue.add(new JsonObjectRequest(Request.Method.GET, URL + "/prod-api/api/common/user/getInfo", null,
                response -> {
                    Log.d(TAG, "onResponse: response" + new String(
                            response.toString().getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8
                    ));
                    liveData.setValue(gson.fromJson(
                            new String(response.toString().getBytes(), StandardCharsets.ISO_8859_1),
                            ResultUser.class
                    ));
                },
                error -> Log.d(TAG, "onErrorResponse: " + error)
        ) {
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> map = new HashMap<>();
                map.put(HEADER_AUTHORIZATION, TOKEN);
                return map;
            }

        });

        return liveData;
    }

    // 获取广告列表
    public LiveData<List<Banner>> ListBanner(Context context, int pageNum, int pageSize, int type) {
        Gson gson = new Gson();
        MutableLiveData<List<Banner>> liveData = new MutableLiveData<>();

        mQueue.add(new StringRequest(Request.Method.GET,
                URL + "/prod-api/api/rotation/list?pageNum=" + pageNum + "&pageSize=" + pageSize + "&type=" + type,
                response -> {
                    String resp = new String(response.getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
                    Log.d(TAG, "onResponse: " + resp);
                    ResultBanner resultBanner = gson.fromJson(resp, ResultBanner.class);
                    liveData.setValue(resultBanner.getRows());
                },
                error -> Log.d(TAG, "onErrorResponse: " + error)
        ));

        return liveData;
    }

    // 获取广告图片
    public LiveData<Bitmap> getBannerImg(Context context, String imageUrl) {
        Gson gson = new Gson();
        MutableLiveData<Bitmap> liveData = new MutableLiveData<>();

        mQueue.add(new ImageRequest(
                URL + "/prod-api/profile/upload/image/2021/05/06/b9d9f081-8a76-41dc-8199-23bcb3a64fcc.png",
                new Response.Listener<Bitmap>() {
                    @Override
                    public void onResponse(Bitmap response) {
                        liveData.setValue(response);
                    }
                }, 100, 100, Bitmap.Config.ARGB_4444,
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Log.d(TAG, "onErrorResponse: " + error);
                    }
                }
        ));

        return liveData;
    }
}
